package org.jeecg.modules.KM.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.KM.VO.DocUserVisitPolicyAddVo;
import org.jeecg.modules.KM.VO.DocUserVisitPolicyEditVo;
import org.jeecg.modules.KM.VO.UserVisitPolicyVo;
import org.jeecg.modules.KM.entity.KmDocVisitPolicy;
import org.jeecg.modules.KM.mapper.KmDocVisitPolicyMapper;
import org.jeecg.modules.KM.service.IKmDocVisitPolicyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@Service
public class KmDocVisitPolicyServiceImpl extends ServiceImpl<KmDocVisitPolicyMapper, KmDocVisitPolicy> implements IKmDocVisitPolicyService {

    @Override
    public Page<UserVisitPolicyVo> queryPageList(Page<UserVisitPolicyVo> page, String docId, String orderBy) {
        Page<UserVisitPolicyVo> ret = getBaseMapper().getPageList(page, docId, orderBy);
        if (ret.getRecords() != null) {
            ret.getRecords().forEach(r -> {
                r.setPolicyTypes(trimPolicyType(r.getPolicyTypes()));
                r.setPolicyTypesDesc(descPolicy(r.getPolicyTypes()));
            });
        }
        return ret;
    }


    /*
    增加文档权限范围
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> addVisitPolicyDoc(DocUserVisitPolicyAddVo docUserVisitPolicyAddVo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            LambdaQueryWrapper<KmDocVisitPolicy> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(KmDocVisitPolicy::getUserId, docUserVisitPolicyAddVo.getVisitPolicyUsers());
            queryWrapper.eq(KmDocVisitPolicy::getDocId, docUserVisitPolicyAddVo.getDocId());
            queryWrapper.select(KmDocVisitPolicy::getUserId);
            List<KmDocVisitPolicy> oldPolicys = this.list(queryWrapper);

            if (!oldPolicys.isEmpty()) {
                oldPolicys.stream().forEach(o -> docUserVisitPolicyAddVo.getVisitPolicyUsers().remove(o.getUserId()));
            }

            List<KmDocVisitPolicy> policies = new ArrayList<>();
            docUserVisitPolicyAddVo.getVisitPolicyUsers().forEach(u -> {
                KmDocVisitPolicy kmDocVisiPolicy = new KmDocVisitPolicy();
                kmDocVisiPolicy.setCreate_by(sysUser.getId());
                kmDocVisiPolicy.setDocId(docUserVisitPolicyAddVo.getDocId());
                kmDocVisiPolicy.setPolicyTypes(trimPolicyType(docUserVisitPolicyAddVo.getVisitPolicys()));
                kmDocVisiPolicy.setUserId(u);
                kmDocVisiPolicy.setAddTime(DateUtils.getDate());
                policies.add(kmDocVisiPolicy);
            });
            if (super.saveBatch(policies))
                return Result.OK();
            else
                return Result.error("保存数据失败");
        } else
            return Result.error("获取登录信息异常");
    }

    @Transactional
    @Override
    public Result<?> updateVisitPolicyDoc(DocUserVisitPolicyEditVo docUserVisitPolicyEditVo) {
        LambdaUpdateWrapper<KmDocVisitPolicy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(KmDocVisitPolicy::getDocId, docUserVisitPolicyEditVo.getDocId());
        updateWrapper.in(KmDocVisitPolicy::getUserId, docUserVisitPolicyEditVo.getVisitPolicyUsers());
        updateWrapper.set(KmDocVisitPolicy::getPolicyTypes, trimPolicyType(docUserVisitPolicyEditVo.getVisitPolicys()));
        if (this.update(updateWrapper)) {
            return Result.OK();
        }
        return Result.error("更新失败");
    }

    /*
    删除文档权限范围
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> delVisitPolicyDoc(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            LambdaQueryWrapper<KmDocVisitPolicy> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(KmDocVisitPolicy::getId, id);
            if (this.count(queryWrapper) != 1)
                return Result.error("数据异常");
            if (getBaseMapper().delete(queryWrapper) > 0)
                return Result.OK();
            else
                return Result.error("删除数据失败");
        } else
            return Result.error("获取登录信息异常");
    }

    private String trimPolicyType(String policyTypes) {
        if (StrUtil.isBlank(policyTypes)) {
            return policyTypes;
        }
        if (policyTypes.endsWith(",")) {
            return policyTypes.substring(0, policyTypes.length() - 1);
        }
        return policyTypes;
    }

    private String descPolicy(String policyTypes) {
        if (StrUtil.isBlank(policyTypes)) {
            return policyTypes;
        }
        StringJoiner sj = new StringJoiner(",");
        for (String t : policyTypes.split(",")) {
            if ("1".equals(t)) {
                sj.add("可见全部");
            } else if ("2".equals(t)) {
                sj.add("部分可见");
            } else if ("3".equals(t)) {
                sj.add("下载");
            }
        }
        return sj.toString();
    }

}
